<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button
        class="filter-item"
        style=""
        type="primary"
        icon="el-icon-edit"
        @click="addProject"
      >
        添加项目
      </el-button>
      <el-input
        v-model="listQuery.title"
        placeholder="请输入关键字"
        style="width: 200px;margin-left:20px;margin-right:20px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>

    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column
        label="项目名称"
        align="center"
      >
        <template slot-scope="{row}">
          <span>{{ row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="省份" align="center">
        <template slot-scope="{row}">
          <span>{{ row.province_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="城市" align="center">
        <template slot-scope="{row}">
          <span>{{ row.city_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="区/县" align="center">
        <template slot-scope="{row}">
          <span>{{ row.area_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="详细地址" align="center">
        <template slot-scope="{row}">
          <span>{{ row.address }}</span>
        </template>
      </el-table-column>
      <el-table-column label="工作时间配置" align="center">
        <template slot-scope="{row}">
          <span>{{ row.created_at }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center">
        <template slot-scope="{row}">
          <span>{{ row.created_username }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.updated_at }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <!-- <el-button type="primary" size="mini" @click="handleUpdate(row)">
            修改
          </el-button> -->
          <el-button size="mini" type="danger" @click="handleDelete(row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="120px" style="width: 430px; margin-left:50px;">
        <el-form-item label="项目名称：" prop="project_title">
          <el-input v-model="temp.project_title" />
        </el-form-item>
        <el-form-item label="地址：">
          <el-cascader
            v-model="selectedOptions"
            size="large"
            style="width:311px"
            :options="options"
            @change="handleChange"
          />
        </el-form-item>
        <el-form-item label="详细地址：" prop="detail_address">
          <el-input v-model="temp.detail_address" />
        </el-form-item>
        <el-form-item label="工作时间配置：" prop="">
          <div style="display:flex">
            <el-checkbox v-model="changeTime_ary[0].change_week" style="margin-right:10px">每周一</el-checkbox>
            <el-time-picker
              v-model="changeTime_ary[0].time"
              is-range
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              placeholder="选择时间范围"
            />
          </div>
          <div class="mt10">
            <el-checkbox v-model="changeTime_ary[1].change_week" style="margin-right:10px">每周二</el-checkbox>
            <el-time-picker
              v-model="changeTime_ary[1].time"
              is-range
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              placeholder="选择时间范围"
            />
          </div>
          <div class="mt10">
            <el-checkbox v-model="changeTime_ary[2].change_week" style="margin-right:10px">每周三</el-checkbox>
            <el-time-picker
              v-model="changeTime_ary[2].time"
              is-range
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              placeholder="选择时间范围"
            />
          </div>
          <div class="mt10">
            <el-checkbox v-model="changeTime_ary[3].change_week" style="margin-right:10px">每周四</el-checkbox>
            <el-time-picker
              v-model="changeTime_ary[3].time"
              is-range
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              placeholder="选择时间范围"
            />
          </div>
          <div class="mt10">
            <el-checkbox v-model="changeTime_ary[4].change_week" style="margin-right:10px">每周五</el-checkbox>
            <el-time-picker
              v-model="changeTime_ary[4].time"
              is-range
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              placeholder="选择时间范围"
            />
          </div>
          <div class="mt10">
            <el-checkbox v-model="changeTime_ary[5].change_week" style="margin-right:10px">每周六</el-checkbox>
            <el-time-picker
              v-model="changeTime_ary[5].time"
              is-range
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              placeholder="选择时间范围"
            />
          </div>
          <div class="mt10">
            <el-checkbox v-model="changeTime_ary[6].change_week" style="margin-right:10px">每周日</el-checkbox>
            <el-time-picker
              v-model="changeTime_ary[6].time"
              is-range
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              placeholder="选择时间范围"
            />
          </div>

        </el-form-item>

        <el-form-item label="报警规则配置：">
          <div style="width:450px">
            <el-checkbox v-model="is_level_alarm" style="margin-right:10px">是否开启逐级上报</el-checkbox>
            未接触警报逐级上报时间间隔：<el-input placeholder="请输入" size="mini" style="width:30px;margin-right:6px" />分钟
          </div>
          <el-checkbox-group v-model="checkList">
            <el-checkbox label="是否小程序报警" />
            <el-checkbox label="是否短信报警" />
            <el-checkbox label="是否电话报警" />
          </el-checkbox-group>
          <div>报警文字提示：</div>
          <el-input v-model="temp.remark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="请输入" style="height:80px" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData('dataForm'):updateData('dataForm')">
          保存
        </el-button>
      </div>
    </el-dialog>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.size"
      @pagination="getList"
    />
  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination'
import { getProjectList, saveAddProject, delProject } from '@/api/projectManage'
import { DefaultQuery, SetDefaultQuery } from '@/utils'
import { regionData, CodeToText } from 'element-china-area-data'
import { log } from '@/utils/log'

export default {
  name: 'ProjectList',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: DefaultQuery({
        // page: 1,
        // size: 10,
        title: ''
      }),
      dialogFormVisible: false,
      temp: {
        id: undefined,
        remark: '',
        project_title: '',
        detail_address: '',
        type: '',
        status: 'published'
      },
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        project_title: [{ required: true, message: '请填写项目名称', trigger: 'blur' }],
        detail_address: [{ required: true, message: '请填写详细地址', trigger: 'blur' }],
        project_address: [{ required: true, message: '请选择地址', trigger: 'blur' }]
      },
      dialogStatus: '',
      textMap: {
        update: '修改项目',
        create: '添加项目'
      },
      options: regionData,
      selectedOptions: [],
      changeTime_ary: [{
        change_week: false,
        time: [new Date(), new Date()],
        day: 1,
        title: '周一'
      }, {
        change_week: false,
        time: [new Date(), new Date()],
        day: 2,
        title: '周二'
      }, {
        change_week: false,
        time: [new Date(), new Date()],
        day: 3,
        title: '周三'
      }, {
        change_week: false,
        time: [new Date(), new Date()],
        day: 4,
        title: '周四'

      }, {
        change_week: false,
        time: [new Date(), new Date()],
        day: 5,
        title: '周五'

      }, {
        change_week: false,
        time: [new Date(), new Date()],
        day: 6,
        title: '周六'
      }, {
        change_week: false,
        time: [new Date(), new Date()],
        day: 7,
        title: '周日'
      }],

      is_level_alarm: false,
      checkList: [],

      province_code: '',
      city_code: '',
      area_code: '',
      province_name: '',
      city_name: '',
      area_name: ''

    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList: function() {
      this.listLoading = true
      getProjectList(this.listQuery).then(data => {
        this.list = data.list
        this.total = data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      // this.listQuery.page = 1
      SetDefaultQuery(this.listQuery)
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetData() {
      this.temp.project_title = ''
      this.province_code = ''
      this.city_code = ''
      this.area_code = ''
      this.province_name = ''
      this.city_name = ''
      this.area_name = ''
      this.temp.detail_address = ''
      this.temp.remark = ''
      this.is_level_alarm = false
      this.checkList = []
      this.selectedOptions = []
      this.changeTime_ary = [{
        change_week: false,
        time: [new Date(), new Date()],
        day: 1,
        title: '周一'
      }, {
        change_week: false,
        time: [new Date(), new Date()],
        day: 2,
        title: '周二'
      }, {
        change_week: false,
        time: [new Date(), new Date()],
        day: 3,
        title: '周三'
      }, {
        change_week: false,
        time: [new Date(), new Date()],
        day: 4,
        title: '周四'

      }, {
        change_week: false,
        time: [new Date(), new Date()],
        day: 5,
        title: '周五'

      }, {
        change_week: false,
        time: [new Date(), new Date()],
        day: 6,
        title: '周六'
      }, {
        change_week: false,
        time: [new Date(), new Date()],
        day: 7,
        title: '周日'
      }]
    },
    addProject() {
      this.dialogFormVisible = true
      this.dialogStatus = 'create'
      this.resetData()
    },
    createData(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const addData = {
            'title': this.temp.project_title,
            'province_code': this.province_code,
            'province_name': this.province_name,
            'city_code': this.city_code,
            'city_name': this.city_name,
            'area_code': this.area_code,
            'area_name': this.area_name,
            'address': this.temp.detail_address,
            'time_rule_type': 1,
            'is_level_alarm': this.is_level_alarm ? 1 : 0,
            'time_rule': [

            ],
            'alarm_template': this.temp.remark ? this.temp.remark : '',
            'alarm_channel': [

            ]
          }
          const timeAry = this.changeTime_ary
          const changeTimeAry = []
          for (let i = 0; i < timeAry.length; i++) {
            if (timeAry[i].change_week) {
              changeTimeAry.push({
                title: timeAry[i].title,
                day: timeAry[i].day,
                start_hour: Number(timeAry[i].time[0].getHours()),
                start_minute: Number(timeAry[i].time[0].getMinutes()),
                end_hour: Number(timeAry[i].time[1].getHours()),
                end_minute: Number(timeAry[i].time[1].getMinutes())

              })
            }
          }
          addData.time_rule = changeTimeAry
          const checkListAry = []
          if (this.checkList.length > 0) {
            this.checkList.forEach(item => {
              if (item === '是否小程序报警') {
                checkListAry.push(1)
              } else if (item === '是否短信报警') {
                checkListAry.push(2)
              } else if (item === '是否电话报警') {
                checkListAry.push(3)
              }
            })
          }
          addData.alarm_channel = checkListAry
          saveAddProject(addData).then(data => {
            if (data) {
              this.dialogFormVisible = false
              this.$message({
                message: '添加成功',
                type: 'success'
              })
              this.getList()
            }
          })
        } else {
          return false
        }
      })
    },
    handleDelete(id) {
      this.$confirm('确定删除该项目?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delProject({
          id
        }).then(data => {
          if (data) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getList()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleChange(value) {
      const [province_code, city_code, area_code] = value
      this.province_code = province_code
      this.city_code = city_code
      this.area_code = area_code
      this.province_name = CodeToText[province_code]
      this.area_name = CodeToText[area_code]
      this.city_name = CodeToText[city_code]
    }
  }
}
</script>
<style lang="scss">
    .filter-container {
        padding-bottom: 20px;
    }
    .mt10 {
        margin-top: 10px;
        display:flex
    }
</style>
